﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApplicationCore.Interfaces;
using ApplicationCore.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Infrastructure.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Infrastructure;

namespace Web
{ 
	/// <summary>
	/// 用户登录日志过滤器
	/// </summary>
	public class AddLoginLogWithFactoryAttribute : Attribute, IFilterFactory
	{
		public OptType LoginOptType { get; set; } 
		 
		private readonly ILogger _logger;
		private   IAsyncRepository<ApplicationUserLoginLog> _repo;
		// Implement IFilterFactory
		public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
		{
			_repo = serviceProvider.GetService<IAsyncRepository<ApplicationUserLoginLog>>();
			return new InternalAddLoginLogFilter(LoginOptType, _repo);
		}

		private class InternalAddLoginLogFilter : IResultFilter
		{
			private readonly ILogger _logger;
			private readonly IAsyncRepository<ApplicationUserLoginLog> _repo;
			private OptType _optType;
			private LogSource _logSource;


			public InternalAddLoginLogFilter(OptType  optType,IAsyncRepository<ApplicationUserLoginLog>  repo) {
				_optType = optType;
				_repo = repo;
				_logSource =  LogSource.Attribute;
			}

			public void OnResultExecuting(ResultExecutingContext context)
			{
				 
			}

			public void OnResultExecuted(ResultExecutedContext context)
			{ 
				if (context.Result is RedirectResult || _optType == OptType.ChatJoined|| _optType==  OptType.ChatLeft)
				{ 
					var userId = context.HttpContext.Request.Form["Email"];
					if (_optType != OptType.SignIn)
					{
						userId = context.HttpContext.User.Identity.Name;
					}


					_repo.AddAsync(new ApplicationUserLoginLog
					{
						OptType = _optType,
						IP = context.HttpContext.GetUserIp(),
						UserId = userId,
						Other = context.HttpContext.Request.Path,
						LogSource = _logSource
					});
				}
			}
		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
	 
	   
}
